from decimal import Decimal
from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework.generics import GenericAPIView, CreateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

from apps.goods.models import SKU
from apps.orders.serializers import OrderPlaceSerializer, OrderCommitSerializer


class OrderPlaceView(GenericAPIView):
    #需要登陆才能访问
    permission_classes = [IsAuthenticated]
    #指定序列化器
    serializer_class = OrderPlaceSerializer


    def get(self,request):

        #获取登陆用户
        user = request.user
        #得到redis对象
        redis_conn=get_redis_connection("cart")
        #得到redis的数据
        sku_id_list=redis_conn.smembers("cart_selcted_%s" %user.id)
        cart_dict = redis_conn.hgetall("cart_%s" % user.id)

        #得到商品对象列表
        sku_list=[]
        for sku_id in sku_id_list:
            sku=SKU.objects.get(id=sku_id)
            sku.count = int(cart_dict[sku_id])
            sku_list.append(sku)

        serializer=self.get_serializer(instance=sku_list,many=True)


        #返回数据
        content={
            "skus":serializer.data,
            "freight":Decimal(10.0)
        }


        return Response(data=content)

#提交订单功能
class OrderCommitView(CreateAPIView):
    serializer_class = OrderCommitSerializer
    permission_classes = [IsAuthenticated]


